<template>
  <div>
    <Dialog :title="formData.id ? '编辑标签' : '新建标签'" v-model="isDialog" :width="550" @confirm="formValidate"
      @close="cancelAdd">
      <el-form :model="formData" :rules="rules" ref="formData" label-width="100px">
        <el-form-item label="标签CODE" prop="propertyKey">
          <el-input type="text" placeholder="请输入数字、字母、下划线" clearable @input="setValue('propertyKey')"
            v-model.trim="formData.propertyKey" maxlength="30" :show-word-limit="true">
          </el-input>
        </el-form-item>
        <el-form-item label="标签名称" prop="propertyName">
          <el-input type="text" placeholder="请输入标签名称" clearable maxlength="30" :show-word-limit="true"
            v-model.trim="formData.propertyName">
          </el-input>
        </el-form-item>
        <el-form-item label="类型" prop="propertyType">
          <el-select v-model="formData.propertyType" placeholder="请选择类型">
            <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 枚举 -->
        <div v-if="formData.propertyType == 4">
          <div class="enumeration" v-for="(item, index) in formData.enumerateValue" :key="index">
            <el-form-item label="key" :prop="'enumerateValue.' + index + '.k'" :rules="rules.k">
              <el-input type="text" placeholder="请输入key" v-model="item.k">
              </el-input>
            </el-form-item>

            <el-form-item label="value" label-width="60px" :prop="'enumerateValue.' + index + '.v'" :rules="rules.v">
              <el-input type="text" placeholder="请输入value" v-model="item.v">
              </el-input>
            </el-form-item>
            <div class="operation">
              <div>
                <el-icon @click="addKeyValue(index)">
                  <CirclePlus />
                </el-icon>
              </div>
              <div>
                <el-icon @click="delKeyValue(index)">
                  <Close />
                </el-icon>
              </div>
            </div>
          </div>
        </div>

        <el-form-item label="选择分组" prop="categoryId">
          <TreeSelect class="_tree_select" v-model="formData.categoryId" :treeSelectData="treeSelectData" :treeProps="{
            label: 'name',
            children: 'children',
            disabled: (data) => {
              return Boolean(data.nodeType && !data.children);
            },
          }" placeholder="请选择分组"></TreeSelect>
        </el-form-item>

        <el-form-item :label="`失效时间`" prop="expireType">
          <el-radio-group v-model="formData.expireType">
            <el-radio v-for="item in tiemRadioList" :key="item.id" :label="item.id">{{ item.name }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="formData.expireType == 'fixed'" :label="`固定时间`" prop="fixed">
          <el-date-picker v-model="formData.fixed" type="datetime" format="YYYY-MM-DD HH:mm:ss" placeholder="请选择固定时间" />
        </el-form-item>

        <div class="relatively" v-if="formData.expireType == 'relatively'">
          <el-form-item :label="`相对时间`" prop="relatively">
            <el-input-number v-model="formData.relatively" :min="1" controls-position="right" placeholder="请输入周期时间">
            </el-input-number>
          </el-form-item>
          <el-form-item label-width="20px">
            <el-select v-model="dataForm.timeType">
              <el-option v-for="item in timeList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </div>

        <!-- <el-form-item label="设为系统标签" prop="classifyType">
          <el-switch
            v-model="formData.classifyType"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </el-form-item> -->
        <el-form-item label="互斥标签">
          <el-select v-model="formData.mutexTagIds" multiple placeholder="请选择互斥标签">
            <el-option v-for="item in tagList" :key="item.id" :label="item.propertyName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" :autosize="{ minRows: 2 }" type="textarea" maxlength="150" show-word-limit
            placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <!-- <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAdd()">取 消</el-button>
          <el-button type="primary" @click="formValidate">确 定</el-button>
        </span>
      </template> -->
    </Dialog>
  </div>
</template>

<script>
import CustomerApi from "@/api/customerApi";
import TreeSelect from "@/components/TreeSelect/TreeSelect.vue";
export default {
  props: {
    isAdd: {
      require: false,
      type: Boolean,
      default: () => {
        return false;
      },
    },
    addData: {
      require: false,
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  watch: {
    isAdd(val) {
      if (val && this.addData.id) {
        this.formData = this.addData;
        console.log("[ this.addData ]", this.addData);

        if (this.formData.mutexTagIds) {
          this.formData.mutexTagIds = this.formData.mutexTagIds
            .split(",")
            .map(Number); // 把数组的每一项转换成数字
        }
        if (this.formData.enumerateValue) {
          this.formData.enumerateValue = JSON.parse(
            this.formData.enumerateValue
          );
        } else {
          this.formData.enumerateValue = [{ k: "", v: "" }];
        }

        if (this.formData.expireType == "relatively") {
          this.formData["relatively"] =
            Number(this.formData.expireTime) / this.dataForm.day;
        } else if (this.formData.expireType == "fixed") {
          this.formData["fixed"] = this.formData.expireTime;

          console.log('[ this.formData["fixed"] ]', this.formData["fixed"]);
        }
      }
      this.isDialog = val;
    },
  },
  data() {
    return {
      isDialog: false,
      treeSelectData: [],
      formData: {
        propertyName: "",
        propertyKey: "",
        classifyType: 0,
        propertyType: "",
        categoryId: "",
        enumerateValue: [],
        expireType: "fixed", // 失效时间
        expireTime: "",
        relatively: "", // 相对时间
        fixed: "", // 固定时间
        mutexTagIds: [],
      },
      tagList: [],
      // tagGroupList: [],
      dataForm: {
        timeType: "day",
        day: 60 * 60 * 24,
      },
      timeList: [
        // {id: '1', name: '年'},
        // {id: '2', name: '月'},
        // {id: '3', name: '周'},
        { id: "day", name: "天" },
        // {id: '5', name: '小时'},
      ],

      tiemRadioList: [
        // { id: "noFailure", name: "不失效" },
        { id: "fixed", name: "固定时间" },
        { id: "relatively", name: "相对时间" },
        { id: "dayEnd", name: "当天失效" },
        { id: "weekEnd", name: "周末失效" },
        { id: "monthEnd", name: "月末失效" },
        { id: "yearEnd", name: "年末失效" },
      ],
      typeList: [
        { id: 0, name: "数字" },
        { id: 1, name: "字符串" },
        { id: 3, name: "时间" },
        { id: 4, name: "枚举" },
      ],
      rules: {
        propertyKey: [
          { required: true, message: "请输入标签CODE", trigger: "blur" },
        ],
        propertyName: [
          { required: true, message: "请输入标签名称", trigger: "blur" },
        ],
        propertyType: [
          { required: true, message: "请选择类型", trigger: "blur" },
        ],
        categoryId: [
          { required: true, message: "请选择分组", trigger: "blur" },
        ],
        fixed: [{ required: true, message: "请选择固定时间", trigger: "blur" }],
        relatively: [
          { required: true, message: "请输入相对时间", trigger: "blur" },
        ],
        k: [
          { required: true, message: "请输入key", trigger: ["blur", "change"] },
        ],
        v: [{ required: true, message: "请输入value", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getTagGroupTree(); // 获取分组
    this.addKeyValue(); // 初始化枚举
    this.getAttributeList(); // 获取标签
  },
  methods: {
    // 获取下拉树的数据
    async getTagGroupTree() {
      let rs = await CustomerApi.getTagGroupTree({ nodeType: "" });
      if (rs.code === 200) {
        this.treeSelectData = rs.payload;
      }
    },
    // async getTagGroupList() {
    //   let rs = await CustomerApi.getTagGroupList();
    //   if (rs.code === 200) {
    //     this.tagGroupList = rs.payload;
    //   }
    // },
    async getAttributeList() {
      let params = {
        currentPage: 1,
        showCount: -1,
      };
      let rs = await CustomerApi.attributeList(params);
      if (rs.code === 200) {
        this.tagList = rs.payload;
      }
    },
    formValidate() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.createOrUpdate();
        } else {
          return false;
        }
      });
    },
    async createOrUpdate() {
      if (this.checkdeKye()) {
        return;
      }
      let params = JSON.parse(JSON.stringify(this.formData));
      if (params.propertyType == 4) {
        params.enumerateValue = JSON.stringify(params.enumerateValue);
      } else {
        params.enumerateValue = "";
      }

      if (params.mutexTagIds) {
        params.mutexTagIds = String(params.mutexTagIds);
      }
      if (params.expireType == "fixed") {
        params.expireTime = new Date(params.fixed).getTime();
      } else if (params.expireType == "relatively") {
        params.expireTime = this.dataForm.day * params.relatively;
      }
      let rs = await CustomerApi.createOrUpdate(params);
      if (rs.code == 200) {
        ElMessage.success(`${this.formData.id ? "编辑" : "添加"}标签成功`);
        this.confirmAdd();
      }
    },
    setValue(propertyKey) {
      this.formData[propertyKey] = this.formData[propertyKey].replace(
        /[^\w_]/g,
        ""
      );
    },

    addKeyValue(index) {
      this.formData.enumerateValue.splice(index + 1, 0, { k: "", v: "" });
    },
    delKeyValue(index) {
      this.formData.enumerateValue.splice(index, 1);
    },
    // 检测key值是否相同
    checkdeKye() {
      let params = this.formData.enumerateValue;
      let isFalse = false;

      for (let index = 0; index < params.length; index++) {
        if (index + 1 !== params.length) {
          if (params[index].k == params[index + 1].k) {
            isFalse = true;
            ElMessage.warning("key不可以重复，请重新填写重复的key");
            // return
          }
        }
      }
      return isFalse;
    },

    cancelAdd() {
      this.$refs.formData.resetFields();
      this.formData = {
        propertyName: "",
        propertyKey: "",
        classifyType: 0,
        propertyType: "",
        categoryId: "",
        enumerateValue: [{ k: "", v: "" }],
        expireType: "noFailure", // 失效时间
        relatively: "", // 相对时间
        fixed: "", // 固定时间
        mutexTagIds: [], // 互斥标签
      };
      this.$emit("cancelAdd");
    },
    confirmAdd() {
      this.$emit("confirmAdd", this.formData.categoryId);
      this.cancelAdd();
    },
  },
};
</script>

<style lang="scss" scoped>
.enumeration {
  display: flex;

  .operation {
    width: 50px;
    font-size: 18px;
    margin: 0 0 18px 5px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .el-icon {
      cursor: pointer;
    }

    .el-icon:hover {
      color: var(--el-color-primary);
    }
  }
}

.el-select {
  width: 100%;
}

.relatively {
  display: flex;
  flex-wrap: nowrap;
}

._tree_select {
  width: 100%;
}
</style>
